package com.example.administrator.daydayappmarket.software.choice.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.example.administrator.daydayappmarket.Contacts;
import com.example.administrator.daydayappmarket.R;
import com.example.administrator.daydayappmarket.recommend.activity.RecommendTopImageSpecialThirdActivity;
import com.example.administrator.daydayappmarket.software.choice.adapter.SoftwareChoiceAdapter;
import com.example.administrator.daydayappmarket.software.choice.adapter.SoftwarePagerAdapter;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoiceAppsItem;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoiceCarousel;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoiceEntry;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoiceParent;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoicePicTopic;
import com.example.administrator.daydayappmarket.software.choice.model.SoftwareChoiceTopicItem;
import com.example.administrator.daydayappmarket.software.utils.CircleIndicator;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * A simple {@link Fragment} subclass.
 */
public class SWChoiceFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2{


    @InjectView(R.id.fragment_software_choice_listView)
    PullToRefreshListView listView;
    @InjectView(R.id.fragment_software_choice_empty_imageView)
    ImageView fragmentSoftwareChoiceEmptyImageView;
    @InjectView(R.id.fragment_software_choice_emptyView)
    RelativeLayout fragmentSoftwareChoiceEmptyView;

    private SoftwareChoiceAdapter adapter;
    private List<SoftwareChoiceParent> data;
    private RequestQueue requestQueue;//Volley请求队列
    private String LISTVIEW_TAG = "string";
    private String LISTVIEW_REFRESH="request1";

    private View headView;
    private SoftwarePagerAdapter headAdapter;
    private List<SoftwareChoiceCarousel> headData;//头视图的ViewPager
    private List<SoftwareChoiceEntry> headData2;//头视图下方的四个图标

    private ImageView imageView1;
    private TextView textView1;

    private ImageView imageView2;
    private TextView textView2;

    private ImageView imageView3;
    private TextView textView3;

    private ImageView imageView4;
    private TextView textView4;
    private ViewPager viewPager;

    private LinearLayout linear1;
    private LinearLayout linear2;
    private LinearLayout linear3;
    private LinearLayout linear4;


    private int page=1;  //用于刷新的id
    private String URL="&pagesize=10";//URL后的拼接



    public SWChoiceFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data = new ArrayList<>();
        headData = new ArrayList<>();
        headData2 = new ArrayList<>();

        page=1;//重新回到这个页面后，将加载数据的页数回到第一页


        requestQueue = Volley.newRequestQueue(getContext());
        refreshData(null);//加载数据


    }

    //加载数据
    private void refreshData(final PullToRefreshBase refreshView) {
        StringRequest request = new StringRequest(Request.Method.GET, Contacts.SOFTWARE_CHOICE+page+URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response != null) {
                    try {
                        Log.e("TAG", "onResponse: ++++++" );
                        //GridView的数据
                        JSONArray jsonArray = new JSONArray(response);

                            JSONObject jsonObject = jsonArray.getJSONObject(2);
                            SoftwareChoiceTopicItem softwareChoiceTopicItem = new SoftwareChoiceTopicItem();
                            softwareChoiceTopicItem.parseJson(jsonObject);
                            data.add(softwareChoiceTopicItem);

                            //ListView的数据
                            JSONObject jsonObject1 = jsonArray.getJSONObject(3);
                            SoftwareChoiceAppsItem softwareChoiceAppsItem = new SoftwareChoiceAppsItem();
                            softwareChoiceAppsItem.parseJson(jsonObject1);
                            data.add(softwareChoiceAppsItem);


                        //获取头视图VIewPager的数据
                        JSONObject jsonObject2 = jsonArray.getJSONObject(0);
                        JSONArray jsonArray1 = jsonObject2.getJSONArray("data");
                        for (int i = 0; i < jsonArray1.length(); i++) {
                            JSONObject jsonObject3 = jsonArray1.getJSONObject(i);
                            SoftwareChoiceCarousel softwareChoiceCarousel = new SoftwareChoiceCarousel();
                            softwareChoiceCarousel.parseJson(jsonObject3);
                            headData.add(softwareChoiceCarousel);
                        }

//                        //获取头视图下方的四个图标的数据
                        JSONObject jsonObject3 = jsonArray.getJSONObject(1);
                        JSONArray jsonArray2 = jsonObject3.getJSONArray("data");
                        for (int i = 0; i < jsonArray2.length(); i++) {
                            JSONObject jsonObject4 = jsonArray2.getJSONObject(i);
                            SoftwareChoiceEntry softwareChoiceEntry = new SoftwareChoiceEntry();
                            softwareChoiceEntry.parseJson(jsonObject4);
                            headData2.add(softwareChoiceEntry);

                        }

                        adapter.notifyDataSetChanged();
                        setHeadView(headView, headData, headData2);


                        if(refreshView!=null){
                            refreshView.onRefreshComplete();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

            }


        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(refreshView!=null){
                    refreshView.onRefreshComplete();
                }

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put(Contacts.HEADER_KEY, Contacts.HEADER_VALUES);
                return map;
            }
        };
        request.setTag(LISTVIEW_TAG);
        requestQueue.add(request);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_swchoice, container, false);
        ButterKnife.inject(this, view);

        adapter = new SoftwareChoiceAdapter(getContext(), data);
        listView.setAdapter(adapter);

        headView = inflater.inflate(R.layout.fragment_software_choice_head, null);
        listView.getRefreshableView().addHeaderView(headView);
        if (headData != null && headData2.size() != 0) {
            setHeadView(headView, headData, headData2);
        }



        Glide.with(getContext()).load(R.drawable.cat_loading_transparent).into(fragmentSoftwareChoiceEmptyImageView);
        listView.setEmptyView(fragmentSoftwareChoiceEmptyView);

        //设置上拉刷新和下拉刷新的模式
        listView.setMode(PullToRefreshBase.Mode.BOTH);
        listView.setOnRefreshListener(this);




        return view;
    }


    //设置头视图
    private void setHeadView(View headView, List<SoftwareChoiceCarousel> headData, final List<SoftwareChoiceEntry> headData2) {
        if (headData != null) {
            headAdapter = new SoftwarePagerAdapter(getContext(), headData);

            viewPager = (ViewPager) headView.findViewById(R.id.fragment_software_head_viewPager);
            viewPager.setAdapter(headAdapter);
            viewPager.setCurrentItem(500/2-(500/2%headData.size()));


//            handler.postDelayed(runnable,5000);
            //初始化头视图的四个ImageView和四个TextView
            initView(headView);

            if(headData2.get(0).getImage().startsWith("http")){
                Glide.with(getContext()).load(headData2.get(0).getImage()).into(imageView1);
            }else{
                Glide.with(getContext()).load(Contacts.FRONT_IMG + headData2.get(0).getImage()).into(imageView1);
            }

            if(headData2.get(1).getImage().startsWith("http")){
                Glide.with(getContext()).load( headData2.get(1).getImage()).into(imageView2);
            }else{
                Glide.with(getContext()).load(Contacts.FRONT_IMG + headData2.get(1).getImage()).into(imageView2);
            }

            if(headData2.get(2).getImage().startsWith("http")){
                Glide.with(getContext()).load(headData2.get(2).getImage()).into(imageView3);
            }else{
                Glide.with(getContext()).load(Contacts.FRONT_IMG + headData2.get(2).getImage()).into(imageView3);
            }

            if(headData2.get(3).getImage().startsWith("http")){
                Glide.with(getContext()).load( headData2.get(3).getImage()).into(imageView4);
            }else{
                Glide.with(getContext()).load(Contacts.FRONT_IMG + headData2.get(3).getImage()).into(imageView4);
            }

            textView1.setText(headData2.get(0).getAlias());
            textView2.setText(headData2.get(1).getAlias());
            textView3.setText(headData2.get(2).getAlias());
            textView4.setText(headData2.get(3).getAlias());


            linear1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(getContext(),RecommendTopImageSpecialThirdActivity.class);
                    String id = headData2.get(0).getId();
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });
            linear2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(getContext(),RecommendTopImageSpecialThirdActivity.class);
                    String id = headData2.get(1).getId();
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });
            linear3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(getContext(),RecommendTopImageSpecialThirdActivity.class);
                    String id = headData2.get(2).getId();
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });
            linear4.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(getContext(),RecommendTopImageSpecialThirdActivity.class);
                    String id = headData2.get(3).getId();
                    intent.putExtra("id",id);
                    startActivity(intent);
                }
            });

            CircleIndicator indicator = (CircleIndicator) headView.findViewById(R.id.fragment_software_head_indicator);
            indicator.setIndicatorMode(CircleIndicator.Mode.OUTSIDE);
            indicator.setIndicatorRadius(5);
            indicator.setIndicatorMargin(3);
            indicator.setViewPager(viewPager, headData.size());
        }
    }


    //设置handler使ViewPager隔5s换一张
//   android.os.Handler handler=new android.os.Handler();
//    Runnable runnable=new Runnable() {
//        @Override
//        public void run() {
//            getActivity().runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
//                }
//            });
//            handler.postDelayed(runnable,5000);
//        }
//    };

    //初始化头视图的四个ImageView和四个TextView
    private void initView(View headView) {
        imageView1 = (ImageView) headView.findViewById(R.id.fragment_software_head_image1);
        imageView2 = (ImageView) headView.findViewById(R.id.fragment_software_head_image2);
        imageView3 = (ImageView) headView.findViewById(R.id.fragment_software_head_image3);
        imageView4 = (ImageView) headView.findViewById(R.id.fragment_software_head_image4);
        textView1 = (TextView) headView.findViewById(R.id.fragment_software_head_text1);
        textView2 = (TextView) headView.findViewById(R.id.fragment_software_head_text2);
        textView3 = (TextView) headView.findViewById(R.id.fragment_software_head_text3);
        textView4 = (TextView) headView.findViewById(R.id.fragment_software_head_text4);
        linear1= (LinearLayout) headView.findViewById(R.id.fragment_software_head_linear1);
        linear2= (LinearLayout) headView.findViewById(R.id.fragment_software_head_linear2);
        linear3= (LinearLayout) headView.findViewById(R.id.fragment_software_head_linear3);
        linear4= (LinearLayout) headView.findViewById(R.id.fragment_software_head_linear4);

    }



    @Override
    public void onResume() {
        super.onResume();
//        handler.postDelayed(runnable,5000);
    }

    @Override
    public void onPause() {
        super.onPause();
//        handler.removeCallbacks(runnable);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        requestQueue.cancelAll(LISTVIEW_TAG);
        requestQueue.cancelAll(LISTVIEW_REFRESH);
    }

    //下拉刷新
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        page=1;
        data.clear();
        headData.clear();
        headData2.clear();
        refreshData(refreshView);
    }

    //上拉刷新
    @Override
    public void onPullUpToRefresh(final PullToRefreshBase refreshView) {
        page++;

        StringRequest request1=new StringRequest(Request.Method.GET, Contacts.SOFTWARE_CHOICE +page + URL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (response != null) {
                    try {
                        JSONArray jsonArray=new JSONArray(response);

                        JSONObject jsonObject1=jsonArray.getJSONObject(0);
                        SoftwareChoicePicTopic softwareChoicePicTopic=new SoftwareChoicePicTopic();
                        softwareChoicePicTopic.parseJson(jsonObject1);
                        data.add(softwareChoicePicTopic);

                        JSONObject jsonObject = jsonArray.getJSONObject(1);
                        SoftwareChoiceAppsItem softwareChoiceAppsItem = new SoftwareChoiceAppsItem();
                        softwareChoiceAppsItem.parseJson(jsonObject);
                        data.add(softwareChoiceAppsItem);


                        adapter.notifyDataSetChanged();

                        refreshView.onRefreshComplete();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {

                Map<String,String> map=new HashMap<>();
                map.put(Contacts.HEADER_KEY,Contacts.HEADER_VALUES);
                return map;
            }
        };

        request1.setTag(LISTVIEW_REFRESH);
        requestQueue.add(request1);



    }
}
